package com.jwd.comm

import javax.servlet.http.HttpServletRequest

/**
 * Created by udi on 2017.3.4.
 */
/*
得到虚拟目录名称
 */
fun HttpServletRequest.getUrlHeader(): String {
    return this.getContextPath() + "/"
}

/**
 *解析Url，可以解析以下类型：
 * ~/abc
 *  ../abc
 *  ./abc
 */
fun HttpServletRequest.resolveUrl(Url: String?): String {
    if (Url == null) return getUrlHeader()
    if (Url.startsWith("~/")) {
        return getUrlHeader() + Url.substring(2)
    }
//    if (Url.startsWith("javascript:")) {
//        return Url
//    }
//
//    if (Url.startsWith("#")) return Url
//
//    if (Url.matches("^\\b(\\w+)\\://".toRegex())) return Url

    if (Url.startsWith("../")) {
        val urlArr = Url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val upLevel = urlArr.count { it === ".." };//  MyObject.Count(MyObject.ToList(String::class.java, urlArr)) { o -> o === ".." }

        var theUrl = this.getRequestURI()
        if (theUrl.endsWith("/") == false) {
            val li = theUrl.lastIndexOf('/')
            if (li <= 0) {
                theUrl = ""
            } else {
                theUrl = theUrl.substring(0, li - 1)
            }
        } else {
            theUrl = theUrl.substring(0, theUrl.length - 2)
        }


        val urlSects = theUrl.split("/".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()

        return urlSects.take(urlSects.size - upLevel - 1).joinToString("/") + "/" + urlArr.slice(upLevel..urlArr.size - 1).joinToString("/");
    }


    return Url
}

/**
 * 解析到物理路径上。
 */
fun HttpServletRequest.serverMapPath(Url: String): String {
    return this.servletContext.getRealPath(Url)
}
